$().ready(function(){
	
    $baseUrl=$("#baseUrl").text();
    
    // Event handlers;
    $.address.change(function(event) {
    	check();
    });
    
    /* Method for checking if the field has the default value*/
    $.validator.addMethod("IsDefault", function(value, element) {
    	return $(element).attr("class").indexOf("descTips") == -1;	
    },"不可以为空哦。。。");
    
    /* Method for date format yyyy-mm-dd HH:MM*/
    jQuery.validator.addMethod(
    		"dateITA",
    		function(value, element) {
    			var check = false;
    			var re = /^\d{4}-\d{2}-\d{2} (([01][0-9])|(2[0123])):(([0-5])([0-9])):(([0-5])([0-9]))$/;
    			if( re.test(value)){
    				var datepart= value.split(' ');
    				var adata = datepart[0].split('-');
    				var gg = parseInt(adata[2],10);
    				var mm = parseInt(adata[1],10);
    				var aaaa = parseInt(adata[0],10);
    				var xdata = new Date(aaaa,mm-1,gg);
    				if ( ( xdata.getFullYear() == aaaa ) && ( xdata.getMonth () == mm - 1 ) && ( xdata.getDate() == gg ) )
    					check = true;
    				else
    					check = false;
    			} else
    				check = false;
    			return this.optional(element) || check;
    		}, 
    		"时间不对哦，请按格式  2012-12-12 20:00:00"
    	);
    
    
    function adjustPicture(){
    	
    	$(".thumbnailContainer img").each(function(){
    		width = $(this).attr("clientWidth");
    		height = $(this).attr("clientHeight");
    		
    		if (width<= 100 && height<= 100) {
    			left = (100-width)/2;
    			top = (100-height)/2;
    			$(this).css("margin-left",left);
    			$(this).css("margin-top",top);
    		} else if (width<=100) {
    			left = (100-width)/2;
    			top = (height-100)/2;
    			$(this).css("margin-left",left);
    			$(this).css("margin-top",-top);
    		} else if (height<=100){
    			left = (width-100)/2;
    			top = (100-height)/2;
    			$(this).css("margin-left",-left);
    			$(this).css("margin-top",top);
    		} else {
    			left = (width-100)/2;
    			top = (height-100)/2;
    			$(this).css("margin-left",-left);
    			$(this).css("margin-top",-top);
    		}
    		
    	});
    }
    
    function fetchTheme(){
    	
    	$.post($baseUrl+ '/invitation/findthemeajax', {
	 		'theme_id' : $("#theme").val(),
	 		'category_id': $("#category").val()
	 	}, function(data) {
	 		$('#choosenThemePreview').remove();
	 		$("#fieldset-step2").after(data);
	 		
	 		//Append the chosen theme's css file 
	 	    $themeCSS = $baseUrl+'/res/css/'+$('#themeCSS').text();
	 		$('link:last').after('<link type="text/css" rel="stylesheet" media="screen" href="'+$themeCSS+'">');
	 		
	 		//Title
	 		if ($("#fieldset-step2 #title").val()=="" || $("#fieldset-step2 #title").val()==$("#fieldset-step2 #title").attr("default")) {
	 			$("#posterTitle").html($("#posterTitle").attr("default"));
	 			$("#fieldset-step2 #title").val($("#fieldset-step2 #title").attr("default")).addClass("descTips");
	 		} else
	 			$("#posterTitle").html($("#fieldset-step2 #title").val());
	 		
	 		//Description
	 		if ($("#fieldset-step2 #description").val()=="" || $("#fieldset-step2 #description").val()==$("#fieldset-step2 #description").attr("default")) {
	 			$("#posterDescription").html($("#posterDescription").attr("default"));
	 			$("#fieldset-step2 #description").val($("#fieldset-step2 #description").attr("default")).addClass("descTips");
	 		}
	 		else
	 			$("#posterDescription").html($("#fieldset-step2 #description").val());
	 		
	 		//Time
	 		if ($("#fieldset-step2 #date").val()=="" || $("#fieldset-step2 #date").val()==$("#fieldset-step2 #date").attr("default") ) {
	 			$("#posterTime span").html($("#posterTime").attr("default"));
	 			$("#fieldset-step2 #date").val($("#fieldset-step2 #date").attr("default")).addClass("descTips");
	 		} else
	 			$("#posterTime span").html($("#fieldset-step2 #date").val());

	 		//Address
	 		if ($("#fieldset-step2 #address").val()=="" || $("#fieldset-step2 #address").val()==$("#fieldset-step2 #address").attr("default")) {
	 			$("#posterPlace span").html($("#posterPlace").attr("default"));
	 			$("#fieldset-step2 #address").val($("#fieldset-step2 #address").attr("default")).addClass("descTips");	 			
	 		} else 
	 			$("#posterPlace span").html($("#fieldset-step2 #address").val());
	 		 	

			//Click the back link
	 		$("#backToStep1").click(function(){
	 			//create 
	 			if (window.location.href.indexOf("edit")== -1)
	 				$.address.value("/");
	 			else //edit
	 				$.address.value("/step1");
	 		});	
	 		

	 		$("#createInvitation").validate({
	 		    	rules: {
	 				title: {IsDefault:true},
	 				date:{IsDefault:true,
	 					dateITA:true},
	 				description:{IsDefault:true},
	 				address:{IsDefault:true}
	 		}
	 		});
	 		 		
	 		 	
	 	
	 	});
 	
    }
    
    function fetchThemesByCategory() {
    	$.ajax({
      		  url: $baseUrl+ '/invitation/fetchthemesbycategoryajax',
      		  type: 'post',
      		  async: false,
      		  data: ({'category_id' : $("#category").val()}),
      		  success: function(data) {
				$('#themePreview').remove();
				$('#theme-element').after(data);

		    	$(".thumbnailContainer img").load(function(){
		    		adjustPicture();
		    	});
      		  }});  
    	
		
    }
    
    //check   
    function check(){
    	

	    //Create page then it's the first step "/"
    	//Edit page then it's the second step "/step1"
    if (((window.location.href.indexOf("edit")== -1) && $.address.value() == "/")
    		|| ((window.location.href.indexOf("edit")!=-1) && $.address.value() == "/step1")){
    	
    	//STEP1
    	
	 	$("#fieldset-step1").show();  //show step1
	 	$("#fieldset-step2").hide();  //hide step2
	 	$('#choosenThemePreview').hide();

    	//haven't chosen any theme
    	if ($("#theme").val() != "") {
    	
    	//step1 	
    		fetchThemesByCategory();	
    	}
        
    	//If the category is changed, the themes would be fetched 
    	$("#category").change(function() {
    		
    		fetchThemesByCategory();
    	});
    	
    	 //click apply, from step1 to step2
   	 	$("#themePreview .apply").live('click',function(){
   	    	
   	    	$("#theme").val($(this).attr('theme_id'));
   	    	
   	    	//create 
 			if (window.location.href.indexOf("edit")== -1)
 				$.address.value('/step2'); 
 			else //edit 
 				$.address.value('/'); 
   	 	});
    	

   	   $("#themePreview .preview").live('click',function(){
   	    	alert($(this).attr('theme_id'));
   	   });
    	
    
   	       //Edit page then it's the first step "/"
   	       //Create page then it's the second step "/step2"
    } else if (((window.location.href.indexOf("edit")!= -1) && $.address.value() == "/")
    		|| ((window.location.href.indexOf("edit")==-1) && $.address.value() == "/step2")){
    	
    	//STEP2
	 	
		fetchTheme();
	 	
	 	$("#fieldset-step1").hide();  //hide step1
	 	$("#fieldset-step2").show();  //show step2
	 	$('#choosenThemePreview').show();
	 			
 		//focus
 		$("#fieldset-step2 input, #fieldset-step2 textarea").focus( function(){
 			if($(this).val() == $(this).attr('default')){$(this).val('').removeClass('descTips');}});
 			
 		//blur
 		$("#fieldset-step2 input, #fieldset-step2 textarea").blur(function(){
	 	if($(this).val() == '') {
	 		
	 		$(this).val($(this).attr('default')).addClass('descTips');
	 		    
	 		if($(this).attr("id") == "title")
	 			$("#posterTitle").html($("#posterTitle").attr("default"));
	 		    
	 		if($(this).attr("id") == "description")
	 			$("#posterDescription").html($("#posterDescription").attr("default"));
	 		   
	 		if($(this).attr("id") == "date")
	 			$("#posterTime span").html($("#posterTime").attr("default"));
	 		  
	 		if($(this).attr("id") == "address")
	 			$("#posterPlace span").html($("#posterPlace").attr("default"));
	 	}
 		});
	 		    

 		function updatePosterTitle(){$("#posterTitle").html($("#fieldset-step2 #title").val());}
 		function updatePosterTime(){$("#posterTime span").html($("#fieldset-step2 #date").val());}
 		function updatePosterDescription(){$("#posterDescription").html($("#fieldset-step2 #description").val());}
 		function updatePosterAddress(){$("#posterPlace span").html($("#fieldset-step2 #address").val());}
 		
 		$("#fieldset-step2 #title").keypress(function(){window.setTimeout(function(){updatePosterTitle();},10);});
 		$("#fieldset-step2 #date").keypress(function(){window.setTimeout(function(){updatePosterTime();},10);});
 		$("#fieldset-step2 #description").keypress(function(){window.setTimeout(function(){updatePosterDescription();},10);});
 		$("#fieldset-step2 #address").keypress(function(){window.setTimeout(function(){updatePosterAddress();},10);});
 		
	 	   	
    }
    }

$("#themePreview .apply, #themePreview .preview, #backToStep1, #Save, #SaveAndAddUser").live('mouseover',function(){$(this).css("cursor","pointer");});
$("#themePreview .apply, #themePreview .preview, #backToStep1, #Save, #SaveAndAddUser").live('mouseout',function(){$(this).css("cursor","default");});

});